package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//初始化每日工单列表
@Component
@Slf4j
public class UserJob {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @XxlJob("taskCountInitJobHandler")
    public ReturnT<String> taskCountInitJobHandler(String param){
        try {
            XxlJobLogger.log("每日工单量初始化");
            userService.list().forEach(user->{
                if(!user.getRoleCode().equals("1001")){//工单执行人排除管理员
                    String key= VMSystem.REGION_TASK_KEY_PREF
                            + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                            +"."+user.getRegionId()    //区域id
                            +"."+user.getRoleCode();   //角色类型
                    //将工单信息作为key，用户id作为value，分数初始化为0，存入redis，进行每日初始化
                    redisTemplate.opsForZSet().add(key,user.getId(),0);
                    redisTemplate.expire(key, Duration.ofDays(1));//设置过期时间为1天；
                }
            });
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            //返回500；
            return ReturnT.FAIL;
        }
    }

}
